/*
 Simple example of making a thread detachable
 */
#include <stdio.h> 
#include <string.h> 
#include <unistd.h>
#include <fibthread.h>

#define SLEEP_TIME 10

void * sleepy_thread(void *);

int main(int argc,char *argv[]){
  int error, get_detach_attr;
  fibthread_attr_t tattr;
  fibthread_t tid;
  
  if ((error = fibthread_attr_init(&tattr)) != 0)
       fprintf(stderr, "Failed to create attribute object: %s\n",
                               strerror(error));
  else if ((error = fibthread_attr_setdetachstate(&tattr,
                         FIBTHREAD_CREATE_DETACHED)) != 0)
       fprintf(stderr, "Failed to set attribute state to detached: %s\n",
                      strerror(error));
  else if ((error = fibthread_create(&tid, &tattr, sleepy_thread, (void*)SLEEP_TIME)) != 0)
       fprintf(stderr, "Failed to create thread: %s\n", strerror(error));
  
  fibthread_yield();


  if ((error = fibthread_attr_getdetachstate(&tattr,
                         &get_detach_attr)) != 0)
       fprintf(stderr, "Failed to get attribute state to detached: %s\n", strerror(error));
  
  printf("The state of detach is DETACHED ? : %d -> %d == %d \n",get_detach_attr == FIBTHREAD_CREATE_DETACHED,get_detach_attr,FIBTHREAD_CREATE_DETACHED);
  

  return 0;
}

void * sleepy_thread(void *arg){
  
  printf("Sleeping Thread ...");
  sleep((int)arg);
  printf("End of Sleep ...");

  return (void *)0;
}

